Ext.define('jwawa.erp.common.CommonSearchModel', {
    extend: 'jwawa.erp.framework.JwawaModel',

    constructor: function(config){
        var me = this;

        Ext.apply(me, config);
        me.callParent(arguments);
        me.addEvents('loadSearchData');

        me.initStore();
    },

    initStore: function(){
        "use strict";
        var me = this;

        me.searchGroupStore = Ext.create('Ext.data.Store',{
            fields: [
                {name: 'id',  type: 'int'},
                'group_name',
                'is_default',
                {name: 'seq',  type: 'int'}
            ],
            autoLoad: false,
            sorters: [{property: 'seq', direction: 'ASC'}]
        });

        me.searchItemStore = Ext.create('Ext.data.Store',{
            fields: [
                {name: 'id',  type: 'int'},
                {name: 'entity_detial_id',  type: 'int'},
                'entity_field_label',
                'entity_field_name',
                'item_class',
                'item_cfg',
                'default_value',
                {name: 'seq',  type: 'int'}
            ],
            autoLoad: false,
            sorters: [{property: 'seq', direction: 'ASC'}]
        });

        me.searchGrpItemShipStore = Ext.create('Ext.data.Store',{
            fields: [
                {name: 'search_group_id',  type: 'int'},
                {name: 'search_item_id',  type: 'int'},
                'default_value',
                {name: 'seq',  type: 'int'}
            ],
            autoLoad: false,
            sorters: [{property: 'seq', direction: 'ASC'}]
        });
    },

    loadSearchData: function(pageCode){
        var me = this;

        Jwawa.framework.JwawaConnection.request({
            url      : '/search/get-all-search-data',
            async    : true,
            jsonData: {page_code: pageCode},
            success : function(response) {
                var data  = response["data"];
                
                data['searchGroupList'].unshift({
                    id: 0,
                    seq: 0,
                    group_name: '-请选择-',
                    is_default: 'N'
                });

                me.searchGroupStore.loadData(data['searchGroupList']);
                me.searchItemStore.loadData(data['searchItemList']);
                me.searchGrpItemShipStore.loadData(data['searchGrpItemShipList']);

                me.fireEvent('loadSearchData', me);
            }
        });
    },

    getDefaultSearchGroupId: function(){
        "use strict";
        var me = this,
            idx = me.searchGroupStore.findExact('is_default', 'Y');

        if(idx >= 0){
            return me.searchGroupStore.getAt(idx).get('id')
        } else {
            return 0;
        }
    },

    getSearchGroupItemShipListByGroupId: function(searchGroupId){
        "use strict";
        var me = this,
            items = [],
            i = 1;

        var searchItemGrpRecords = me.searchGrpItemShipStore.queryBy(function(record, id){
            if(record.get('search_group_id') == searchGroupId){
                return true;
            }else{
                return false;
            }
        });

        searchItemGrpRecords.each(function(sigr){
            items.push({
                search_group_id: me.currentSearchGroupId,
                search_item_id:  sigr.get('search_item_id'),
                default_value: sigr.get('default_value'),
                seq: i++
            });
        });

        return items;
    },

    saveSearchGroup: function(searchGroup, opt){
        "use strict";
        var me = this,
            optional = me.buildOpt(opt);

        Jwawa.framework.JwawaConnection.request({
            url      : '/search/save-search-group',
            async    : false,
            jsonData : searchGroup,
            success : function(response) {
                var tmpSearchGroup = me.searchGroupStore.getById(searchGroup['id']);
                if(Ext.isEmpty(tmpSearchGroup)){
                    searchGroup['id'] =  response.data['id'];
                    searchGroup['seq'] = me.searchGroupStore.max('seq') + 1;
                    me.searchGroupStore.add({
                        id: searchGroup['id'],
                        group_name: searchGroup['group_name'],
                        is_default: searchGroup['is_default'],
                        seq: searchGroup['seq']
                    });
                }else{
                    tmpSearchGroup.set('group_name', searchGroup['group_name']);
                    tmpSearchGroup.set('is_default', searchGroup['is_default']);
                }

                optional['success'](searchGroup);
            },
            failure: function(response){
                optional['failure'](response);
            },
            callback: function(options, success, response){
                optional['callback'](response);
            }
        });
    },

    deleteSearchGroup: function(deleteSearchGroupIdList, opt){
        var me = this,
            optional = me.buildOpt(opt);

        Jwawa.framework.JwawaConnection.request({
            url      : '/search/delete-search-group',
            async    : false,
            jsonData : deleteSearchGroupIdList,
            success : function(response) {
                Array.forEach(deleteSearchGroupIdList, function(deleteSearchGroupId){
                    // delete relationship between searchGroup & searchItem
                    var searchItemGrpRecords = me.searchGrpItemShipStore.queryBy(function(record, id){
                        if(record.get('search_group_id') == deleteSearchGroupId){
                            return true;
                        }else{
                            return false;
                        }
                    });
                    searchItemGrpRecords.remove(searchItemGrpRecords);

                    var searchGroup = me.searchGroupStore.getById(deleteSearchGroupId);
                    me.searchGroupStore.remove(searchGroup);
                });

                optional['success'](response);
            }
        });
    },

    setDefaultSearchGroup: function(searchGroupId, opt){
        var me = this,
            optional = me.buildOpt(opt);

        Jwawa.framework.JwawaConnection.request({
            url      : '/search/set-default-search-group',
            async    : false,
            jsonData : {
                'group_id' : searchGroupId
            },
            success : function(response) {
                var oDefautSearchGroupId = me.getDefaultSearchGroupId();
                if(!Ext.isEmpty(oDefautSearchGroupId) && oDefautSearchGroupId > 0){
                    var oDefautSearchGroup = me.searchGroupStore.getById(oDefautSearchGroupId);
                    oDefautSearchGroup.set('is_default', 'N');
                    oDefautSearchGroup.commit();
                }

                var nDefaultSearchGroup = me.searchGroupStore.getById(searchGroupId);
                nDefaultSearchGroup.set('is_default', 'Y');
                nDefaultSearchGroup.commit();

                optional['success'](response);
            }
        });
    },

    saveSearchGroupItemShip: function(sarchGroupId, sarchGroupItemShipList, opt){
        var me = this,
            optional = me.buildOpt(opt);

        Jwawa.framework.JwawaConnection.request({
            url      : '/search/save-search-group-item-ship',
            async    : true,
            jsonData : {
                searchGroupId: sarchGroupId,
                sarchGroupItemShipList: sarchGroupItemShipList
            },
            success : function(response) {
                var tmpDelRec = me.searchGrpItemShipStore.queryBy(function(searchGroupItem){
                    if(searchGroupItem.get('search_group_id') == sarchGroupId){
                        return true;
                    } else {
                        return false;
                    }

                });
                me.searchGrpItemShipStore.remove(tmpDelRec.items);
                me.searchGrpItemShipStore.add(sarchGroupItemShipList);

                optional['success'](response);
            },
            callback: function(options, success, response){
                optional['callback'](response);
            }
        });
    }
});
